package com.app.couponsharelife.utils

import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager

/**
 *Created by xct on 2018/12/8
 *Description:
 */
class KeyboardPatch(act: Activity, contentView: View) {
    private var activity=act
    private var decorView=act.window.decorView
    private var temp = 0
    /**
     * 构造函数
     *
     * @param act         需要解决bug的activity
     * @param contentView 界面容器，activity中一般是R.id.content，也可能是Fragment的容器，根据个人需要传递
     */
    /**
     * 监听layout变化
     */
    fun enable() {
        activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        if (Build.VERSION.SDK_INT >= 19) {
            decorView.viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
        }
    }

    /**
     * 取消监听
     */
    fun disable() {
        activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        if (Build.VERSION.SDK_INT >= 19) {
            decorView.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
        }
    }

    private val onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
        val r = Rect()

        decorView.getWindowVisibleDisplayFrame(r)
        val height = decorView.context.resources.displayMetrics.heightPixels
        var diff = height - r.bottom
        if (diff < 0) {
            temp = -diff
            diff = 0
        }
        if (diff != 0) {
            //Log.e("TAG", "diff:$diff")
            if (contentView.paddingBottom != diff) {
                contentView.setPadding(0, 0, 0, diff + temp)
            }
        } else {
            //Log.e("TAG", "diff:$diff")
            if (contentView.paddingBottom != 0) {
                contentView.setPadding(0, 0, 0, 0)
            }
        }
    }
}